package com;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;

public class ClientThread extends PublicThread {
	private boolean isConnect = false;
	private ServerThread server = null;

	public ClientThread(ServerSocket serverSocket, ThreadPool pool) {
		this.threadPool = pool;
		this.serverSocket = serverSocket;

		addToThreadPool();
	}

	public void run() {
		InputStream in = null;
		byte[] data = new byte[4096];
		int lenght = 0;
		try {
			System.out.println("Waiting Client Connect, Port: " + serverSocket.getLocalPort());
			socket = serverSocket.accept();
			System.out.println("new Client Connect, Address: " + socket.getInetAddress().getHostAddress() + ", Port: "
					+ socket.getPort());
			this.server.newThreadStrat();

			isConnect = true;
			try {
				in = socket.getInputStream();
				while (isRun && lenght > -1) {
					lenght = in.read(data);
					if (lenght > 0) {
						String o = new String(data);
						server.send(data, 0, lenght);
						System.out.println("Data:  " + o.substring(0, o.length() > 20 ? 20 : o.length()));
					}
					sleep(10);
				}
				server.close();
				System.out.println("Remote Close MainClient, Address: " + socket.getInetAddress().getHostAddress()
						+ ", Port: " + socket.getPort());
			} catch (IOException e) {
				System.out.println("ServerThread Error " + e.getMessage());
			}
			socket = null;
			sleep(10);
		} catch (IOException e) {
			System.out.println("ServerThread Error " + e.getMessage());
		}

		isConnect = false;
		close();
		removeFromThreadPool();
	}

	public void close() {
		synchronized (this) {
			try {
				super.closeThread();
			} catch (Exception e1) {
				System.out.print("close MainClinetThread socket Error, Port:" + serverSocket.getLocalPort());
			}
		}
	}

	public void serServer(ServerThread server) {
		this.server = server;
	}

	public int getPort() {
		return serverSocket.getLocalPort();
	}

	public boolean isConnect() {
		return this.isConnect;
	}

	public void send(byte[] data, int s, int l) {
		synchronized (this) {
			if (socket != null) {
				try {
					socket.getOutputStream().write(data, s, l);
				} catch (IOException e) {
					System.out.println(e.getMessage() + "ClientThread Send Data Error, Address: "
							+ socket.getInetAddress().getHostAddress() + ", Port: " + socket.getPort());
				}
			}
		}
	}

}
